package com.atguigu.gmall.pay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.filter.IFilterConfig;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.util.JsonUtil;
import com.atguigu.gmall.feign.order.OrderFeign;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.pay.config.AlipayProperties;
import com.atguigu.gmall.pay.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2025/9/15 20:42
 */
@Slf4j
@Service
public class PayServiceImpl implements PayService {
    @Autowired
    OrderFeign orderFeign;
    @Autowired
    AlipayClient alipayClient;
    @Autowired
    AlipayProperties alipayProperties;

    @Override
    public String alipaySubmit(Long orderId) throws AlipayApiException {

        Result<OrderInfo> orderInfoResult = orderFeign.infoById(orderId);
        if (orderInfoResult.isOk()) {
            OrderInfo orderInfo = orderInfoResult.getData();
            //调用支付宝接口，生成支付链接
            Map<String, String> resultMap = getBizContent(orderInfo);
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            request.setReturnUrl(alipayProperties.getReturn_url());
            request.setNotifyUrl(alipayProperties.getNotify_url());
            request.setBizContent(JsonUtil.toStr(resultMap));
            String body = alipayClient.pageExecute(request).getBody();
            return body;
        }
        return null;
    }
    //通过验签，验证该回调是否是支付宝发出的
    @Override
    public Boolean checkAliPaySign(Map<String, String> params) throws AlipayApiException {
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipay_public_key(), alipayProperties.getCharset(), alipayProperties.getSign_type()); //调用SDK验证签名
        return signVerified;
    }
    //查询订单状态
    @Override
    public String checkOrderStatus(String outTradeNo) throws AlipayApiException {
        // 构造请求参数以调用接口
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("out_trade_no", outTradeNo);
        request.setBizContent(jsonObject.toJSONString());
        // 第三方代调用模式下请设置app_auth_token
        // request.putOtherTextParam("app_auth_token", "<-- 请填写应用授权令牌 -->");

        AlipayTradeQueryResponse response = alipayClient.execute(request);


        if (response.isSuccess()) {
            log.info("查询成功，订单状态：{}", response.getTradeStatus());
            return response.getTradeStatus();
        } else {
            log.error("查询失败，订单状态：{}", response.getTradeStatus());
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
            return null;
        }
    }

    private Map<String, String> getBizContent(OrderInfo orderInfo) {
        Map<String, String> map = new HashMap<>();
        map.put("out_trade_no", orderInfo.getOutTradeNo());
        map.put("total_amount", orderInfo.getTotalAmount().toPlainString());
        map.put("subject", orderInfo.getTradeBody());
        map.put("product_code", "FAST_INSTANT_TRADE_PAY");
        Date expireTime = orderInfo.getExpireTime();
        String date = DateUtil.formatDate(expireTime, "yyyy-MM-dd HH:mm:ss");
        map.put("time_expire",date);
        return map;
    }
}
